package com.glsc.ngateway.platform.service.it;

import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.dto.system.SystemMainDto;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItDict;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItDictData;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItDictDataRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItDictRepo;
import com.glsc.ngateway.platform.service.system.SystemMainService;
import com.glsc.ngateway.platform.utils.SpecificationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class DictionaryService {

    private static final Logger logger = LoggerFactory.getLogger(DictionaryService.class);


    @Resource
    private ItDictRepo itDictRepo;

    @Resource
    private ItDictDataRepo itDictDataRepo;

    @Resource
    private SystemMainService systemMainService;


    //根据条件查询所有字典
    public List<ItDictData> findAll(Map<String, Object> param) {
        return itDictDataRepo.findAll(SpecificationUtil.buildSpecification(param, ItDictData.class));
    }

    /**
     * 分页条件查询
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<ItDictData> findPage(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "dictId";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        return itDictDataRepo.findAll(SpecificationUtil.buildSpecification(param, ItDictData.class), pageable);
    }


    /**
     * 根据ID查询
     *
     * @param dictId
     * @return
     */
    public ItDictData findById(Integer dictId) {
        Optional<ItDictData> optional = itDictDataRepo.findById(dictId);
        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
        }
    }

    /**
     * 根据dictData查询
     *
     * @param dictData
     * @return
     */
    public ItDictData findByDictData(String dictData) {
        if (DictConstant.DICT_V_SYSTEM_ID.equals(dictData)) {//系统编码虚拟字典
            return buildVDictSystemId();
        }
        if (DictConstant.DICT_V_GITEE_PROGRAM_ID.equals(dictData)) {//
            return buildVDictGiteeProgramId();
        }

        ItDictData byDictData = itDictDataRepo.findByDictData(dictData);
        return byDictData;
    }

    /**
     * 根据dictName查询
     *
     * @param dictName
     * @return
     */
    public ItDictData findByDictName(String dictName) {
        ItDictData byDictName = itDictDataRepo.findByDictName(dictName);
        return byDictName;
    }

    //实体创建、更新
    @Transactional(rollbackFor = Exception.class)
    public ItDictData save(ItDictData itDictData) {
        return itDictDataRepo.save(itDictData);
    }

    //删除
    public void delete(ItDictData itDictData) {
        itDictDataRepo.delete(itDictData);
    }

    //字典项实体的更新service
    @Transactional(rollbackFor = Exception.class)
    public ItDict saveDictValues(ItDict itDict) {
        return itDictRepo.save(itDict);
    }

//======================================以上为新的API==========================================================================


    //查询字典内页面
    public Page<ItDict> queryDictList(Integer page, Integer size, String dictData) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<ItDict> list = itDictRepo.getDict(pageable, dictData);
        return list;
    }


    public Map<String, String> getItDictDataRepo(String dict) {
        Map<String, String> dictMap = itDictRepo.getDicts(dict).stream().collect(Collectors.toMap(ItDict::getDictSubentry, ItDict::getDictValue, (key1, key2) -> key2));
        return dictMap;
    }

    /**
     * 添加或者更新字典值
     */
    public void addOrUpdateDict(ItDict itDict) {
        itDictRepo.save(itDict);
    }

    /**
     * 删除字典值
     */
    public void deleteDict(String zdId) {
        ItDict it = itDictRepo.findByZdId(Integer.parseInt(zdId));
        if (it != null) {
            itDictRepo.delete(it);
        }
    }

    /**
     * 分页查询代理
     *
     * @param queryList   查询集合
     * @param constructor 对查询结果进行构造
     */
    public <T> List<ItDict> pageByTypeAdapter(List<T> queryList, Function<T, ItDict> constructor) {
        return queryList.stream().map(constructor).collect(Collectors.toList());
    }

    public ItDict findByDictEntryAndDictSubentry(String dictEntry, String dictSubentry) {
        return itDictRepo.findByDictEntryAndDictSubentry(dictEntry, dictSubentry).stream().findFirst().orElse(null);
    }

/////////////////////////////////////////
//	//查询字典内品牌页面
//	public List<Map<String, Object>> queryAllByDictData(String dictId) {
//		String sql = "select a.zd_id,a.dict_value from t_dict a,t_dictdata b where a.dict_entry=b.dict_id and b.dict_id=?";
//		//List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql, new Object[] {opUser});   测试看是否有数据
//		return BeanUtil.underline2Camel(jdbcTemplate.queryForList(sql, new Object[] {dictId}));
//	}
//
/////////////////////////////////////////
////查询字典内品牌页面
//	public List<Map<String, Object>> queryDictDataList() {
//		String sql = "select dict_id,dict_data from t_dictdata";
//		//List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql, new Object[] {opUser});   测试看是否有数据
//		return BeanUtil.underline2Camel(jdbcTemplate.queryForList(sql));
//	}
//
//
/////////////////////////////////////////
//
//
//	//更新字典值
//	public void updateDict(Map<String, Object> dictInfo) {
//		dictInfo = BeanUtil.camel2Underline(dictInfo);
//		generalDataManager.update("t_dict", dictInfo, "zd_id");
//	}
//
//
//
//	//添加字典值（自增序列）
//	public void addDict(Map<String, Object> dictInfo) {
//		dictInfo = BeanUtil.camel2Underline(dictInfo);
//		generalDataManager.insert("t_dict", dictInfo);
//	}
//
//
//	//删除字典值
//	public void deleteDict(int zdId) {
//		String sql = "delete from t_dict where zd_id=?";
//		jdbcTemplate.update(sql, new Object[] { zdId });
//	}


    /**
     * 构造项目编码字典
     */
    private ItDictData buildVDictSystemId() {
        List<SystemMainDto> systemMainDtoList = systemMainService.findAllBySystemIdNotNull();

        ItDictData dict = new ItDictData();
        dict.setDictData(DictConstant.DICT_V_SYSTEM_ID);
        List<ItDict> dictItemList = new ArrayList<>();
        systemMainDtoList.forEach(systemMainDto -> {
            ItDict item = new ItDict();
            item.setDictEntry(DictConstant.DICT_V_SYSTEM_ID);
            item.setDictSubentry(systemMainDto.getSystemId());
            item.setDictValue(systemMainDto.getOpName());
            dictItemList.add(item);
        });
        dict.setDictValues(dictItemList);
        return dict;
    }

    /**
     * 构造Gitee项目Id字典
     */
    private ItDictData buildVDictGiteeProgramId() {
        List<SystemMainDto> systemMainDtoList = systemMainService.findAllByProgramIdNotNull();

        ItDictData dict = new ItDictData();
        dict.setDictData(DictConstant.DICT_V_GITEE_PROGRAM_ID);
        List<ItDict> dictItemList = new ArrayList<>();
        systemMainDtoList.forEach(systemMainDto -> {
            ItDict item = new ItDict();
            item.setDictEntry(DictConstant.DICT_V_GITEE_PROGRAM_ID);
            item.setDictSubentry(systemMainDto.getProgramId());
            item.setDictValue(systemMainDto.getOpName());
            dictItemList.add(item);
        });
        dict.setDictValues(dictItemList);
        return dict;
    }

}
